package com.lzk.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
	private int width = 160;
	private int height = 40;
	private String code = new String();
	private BufferedImage bufferedImage;
	private String str = "0123456789abcdefg";
	
	public String getCode() {
		return code;
	}
	
	public VerifyCode() {
		bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics2D g = bufferedImage.createGraphics();//����
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		Font font = new Font("",Font.BOLD,22);
		g.setFont(font);
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width - 1, height - 1);
		Random random = new Random();
		for (int i = 1; i <= 4; i++) {
			g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
			char c = str.charAt(random.nextInt(str.length()));
			int h = random.nextInt(5) + 25;//25--35
			g.drawString(c + "", width/4*i-(width/8), h);
			code += c;
		}
		for (int i = 0; i < 6; i++) {
			g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
			int x1 = random.nextInt(width);
			int x2 = random.nextInt(width);
			int y1 = random.nextInt(height);
			int y2 = random.nextInt(height);
			g.drawLine(x1, y1, x2, y2);
		}
	}
	
	public String getImg() {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		try {
			ImageIO.write(bufferedImage, "png", stream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String base64 = Base64.getEncoder().encodeToString(stream.toByteArray());
		try {
			stream.flush();
			stream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "data:image/png;base64," + base64;
		
	}
}
